package util;/*
 * Copyright (c) 1994-2017, Joyoung Stock CO.LTD.
 * The FWJR Project.
 * All Rights Reserved.
 */


import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetworkUtil {

    private static NetworkInfo getActiveNetworkInfo(Context context) {
        if (context != null) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivityManager != null) {
                return connectivityManager.getActiveNetworkInfo();
            }
        }
        return null;
    }


    /**
     * 获取当前网络连接的类型
     *
     * @return 当前网络类型
     */
    private static int getConnectedType(Context context) {
        NetworkInfo networkInfo = getActiveNetworkInfo(context);
        if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
            return networkInfo.getType();
        }
        return -1;
    }

    /**
     * 判断网络连接是否可用
     */
    public static boolean isNetworkAvailable(Context context) {
        NetworkInfo networkInfo = getActiveNetworkInfo(context);
        return networkInfo != null && networkInfo.isAvailable();
    }

    /**
     * 判断是否正在使用2G/3G/4G数据网络
     */
    public static boolean isMobileNetworkConnectedOrConnecting(Context context) {
        return getConnectedType(context) == ConnectivityManager.TYPE_MOBILE;
    }

    /**
     * 判断是否正在使用2G/3G/4G数据网络
     */
    public static boolean isWifiConnectedOrConnecting(Context context) {
        return getConnectedType(context) == ConnectivityManager.TYPE_WIFI;
    }

}
